/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ReportPanel.java
 *
 * Created on 2011-11-15, 15:31:44
 */

package Visual;

import USBThermometerLib.Sensor;
import Main.Main;
import Tools.ConfigurationManager;
import Tools.CharsetControl;
import Visual.Tools.ExtensionFileFilter;
import Visual.Tools.HtmlReportFactory;
import Visual.Tools.InternalFrameObservable;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

/**
 *
 * @author pawelkn
 */
public class ReportPanel extends javax.swing.JPanel implements DropTargetListener {
    private static ResourceBundle bundle;

    private Component parent;
    private final List<Sensor> sensors = Collections.synchronizedList(new ArrayList<Sensor>());

    private final ReportSettingsDialog rsd;

    /** Creates new form ReportPanel */
    public ReportPanel(Component parent) {
        this.parent = parent;

        Locale locale = new Locale( ConfigurationManager.load().getLocale() );
        ResourceBundle.clearCache();
        bundle = ResourceBundle.getBundle("Bundle", locale, new CharsetControl());

        initComponents();

        rsd = new ReportSettingsDialog(MainForm.getInstance(), true);

        HTMLEditorKit kit = new HTMLEditorKit();
        jEditorPane1.setEditorKit(kit);
        jEditorPane1.setContentType("text/html"); // lets Java know it will be HTML
        jEditorPane1.setEditable(false);
        HTMLDocument doc = (HTMLDocument)jEditorPane1.getDocument();
        doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
        File currentDir = new File( System.getProperty( "user.dir" ) + "/report");

        try {
            doc.setBase(currentDir.toURI().toURL());
        } catch (MalformedURLException ex) {
            Logger.getLogger("USBThermometer").log(Level.ALL, null, ex);
        }

        update();

        jEditorPane1.setDropTarget(new DropTarget(this,this));
        this.setDropTarget(new DropTarget(this,this));
    }

    private synchronized void update() {
        final Cursor previousCursor = getCursor();
        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        
        Thread th = new Thread(new Runnable() {
            @Override
            public void run() {
                updateFrameTitle();

                HtmlReportFactory hrf = new HtmlReportFactory(sensors, rsd.getPeriodLowDate(), rsd.getPeriodHighDate());
                jEditorPane1.setText(hrf.build()); // sets its text

                setCursor(previousCursor);
            }
        });

        th.start();
    }

    protected void updateFrameTitle() {
        InternalFrameObservable ifo = ((InternalFrameObservable)parent);
        if (sensors.size() == 0) {
            ifo.setTitle(bundle.getString("REPORT"));
            ifo.notifyTitleChanged(bundle.getString("REPORT"));
        } else if (sensors.size() == 1) {
            ifo.setTitle(bundle.getString("REPORT_-_") + sensors.get(0).getName());
            ifo.notifyTitleChanged(bundle.getString("REPORT_-_") + sensors.get(0).getName());
        } else {
            ifo.setTitle(bundle.getString("REPORT_-_") + sensors.get(0).getName() + ", ...");
            ifo.notifyTitleChanged(bundle.getString("REPORT_-_") + sensors.get(0).getName() + ", ...");
        }
    }

    public void close() {
        MainForm.getInstance().removeVisualElement(parent);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jEditorPane1 = new javax.swing.JEditorPane();
        jToolBar1 = new javax.swing.JToolBar();
        jButton4 = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        jButton3 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jToolBar2 = new javax.swing.JToolBar();

        jScrollPane1.setViewportView(jEditorPane1);

        jToolBar1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        jButton4.setIcon(new ImageIcon("graphics/clock--pencil.png"));
        jButton4.setBorder(javax.swing.BorderFactory.createEmptyBorder(3, 3, 3, 3));
        jButton4.setFocusable(false);
        jButton4.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton4.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton4);
        jToolBar1.add(jSeparator2);

        jButton3.setIcon(new ImageIcon("graphics/disk-black.png"));
        jButton3.setBorder(javax.swing.BorderFactory.createEmptyBorder(3, 3, 3, 3));
        jButton3.setFocusable(false);
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton3);
        jToolBar1.add(jSeparator1);

        jButton1.setIcon(new ImageIcon("graphics/arrow-circle-double-135.png"));
        jButton1.setBorder(javax.swing.BorderFactory.createEmptyBorder(3, 3, 3, 3));
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton1);

        jButton2.setIcon(new ImageIcon("graphics/cross-script.png"));
        jButton2.setBorder(javax.swing.BorderFactory.createEmptyBorder(3, 3, 3, 3));
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton2);

        jToolBar2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jToolBar2.setFloatable(false);
        jToolBar2.setRollover(true);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        update();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        int count = sensors.size();
        Object[] possibilities = new Object[count];
        for( int i = 0; i < count; i++ ) {
            possibilities[i] = sensors.get(i).getName();
        }

        String s = (String)JOptionPane.showInputDialog(
                            parent,
                            bundle.getString("SELECT_A_SENSOR_TO_REMOVE:"),
                            bundle.getString("REMOVE_SENSOR"),
                            JOptionPane.PLAIN_MESSAGE,
                            null,
                            possibilities,
                            null);

        if( s != null ) {
            for( Sensor sensor : sensors ) {
                if(s.equals(sensor.getName())) {
                    sensors.remove(sensor);
                    update();
                    return;
                }
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        rsd.setVisible(true);
        update();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        String wd = System.getProperty("user.dir");
        JFileChooser fc = new JFileChooser(wd);
        FileFilter filter1 = new ExtensionFileFilter(bundle.getString("HTML_FILES_(*.HTML)"), new String[] { "HTML" });
        fc.setFileFilter(filter1);
        int rc = fc.showDialog(null, bundle.getString("SAVE"));
        if (rc == JFileChooser.APPROVE_OPTION) {
            File f = fc.getSelectedFile();
            String filePath = f.getPath();
            if(!filePath.toLowerCase().endsWith(".html"))
            {
                f = new File(filePath + ".html");
            }

            String directory = f.getParent();
            File cssNewFile = new File( directory + "\\" + HtmlReportFactory.CSS_FILE.getName());
            File graphNewFile = new File( directory + "\\" + HtmlReportFactory.GRAPH_FILE.getName());


            try {
                Files.copy(HtmlReportFactory.REPORT_FILE.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
                Files.copy(HtmlReportFactory.CSS_FILE.toPath(), cssNewFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                Files.copy(HtmlReportFactory.GRAPH_FILE.toPath(), graphNewFile.toPath() , StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException ex) {
                Logger.getLogger("USBThermometer").log(Level.ALL, null, ex);
            }

        }
        return;
    }//GEN-LAST:event_jButton3ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JEditorPane jEditorPane1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    // End of variables declaration//GEN-END:variables

    @Override
    public void dragEnter(DropTargetDragEvent arg0) {
    }

    @Override
    public void dragOver(DropTargetDragEvent arg0) {
    }

    @Override
    public void dropActionChanged(DropTargetDragEvent arg0) {
    }

    @Override
    public void dragExit(DropTargetEvent arg0) {
    }

    @Override
    public void drop(DropTargetDropEvent dtde) {
        List<DataFlavor> df = dtde.getCurrentDataFlavorsAsList();
        Transferable tr = dtde.getTransferable();
        for(DataFlavor d : df) {
            try {
                Object list = tr.getTransferData(d);
                if( list instanceof String ) {
                    Sensor newSensor = Main.findSensorByName((String)list);
                    if( ( newSensor != null ) && ( !sensors.contains(newSensor) ) ) {
                        sensors.add(newSensor);
                        update();
                        return;
                    }
                }
            } catch (Exception ex) {
                Logger.getLogger("USBThermometer").log(Level.ALL, null, ex);
            }
        }
    }

}
